package com.luyue.zagj.activity.home;

import android.Manifest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.luyue.zagj.BaseActivity;
import com.luyue.zagj.R;
import com.luyue.zagj.service.GPSService;
import com.luyue.zagj.utils.ToastUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class CallPoliceActivity extends BaseActivity {

    private static final int ACCESS_FINE_LOCATION = 1;
    @Bind(R.id.call_police_cancel_btn)
    Button callPoliceCancelBtn;
    @Bind(R.id.call_police_top_rl)
    RelativeLayout callPoliceTopRl;
    @Bind(R.id.call_police_img)
    ImageView callPoliceImg;
    @Bind(R.id.call_police_brand)
    TextView callPoliceBrand;
    @Bind(R.id.call_police_license)
    TextView callPoliceLicense;
    @Bind(R.id.call_police_time)
    TextView callPoliceTime;
    @Bind(R.id.call_police_pos)
    TextView callPolicePos;
    @Bind(R.id.call_police_lost_time)
    EditText callPoliceLostTime;
    @Bind(R.id.time_picker)
    ImageView timePicker;
    @Bind(R.id.call_police_lost_date)
    EditText callPoliceLostDate;
    @Bind(R.id.date_picker)
    ImageView datePicker;
    @Bind(R.id.call_police_lost_pos)
    EditText callPoliceLostPos;
    @Bind(R.id.call_police_lost_name)
    EditText callPoliceLostName;
    @Bind(R.id.call_police_phone)
    EditText callPolicePhone;
    @Bind(R.id.call_police_other_msg)
    EditText callPoliceOtherMsg;
    @Bind(R.id.call_police_first)
    TextView callPoliceFirst;
    /*@Bind(R.id.call_police_second)
    TextView callPoliceSecond;
    @Bind(R.id.call_police_third)
    TextView callPoliceThird;*/
    /*@Bind(R.id.call_police_lv)
    EasyRecyclerView callPoliceLv;*/
    @Bind(R.id.call_police_sure_cb)
    CheckBox callPoliceSureCb;
    @Bind(R.id.call_police_sure_tv)
    TextView callPoliceSureTv;
    @Bind(R.id.call_police_scroll)
    ScrollView callPoliceScroll;
    @Bind(R.id.pop_anima)
    LinearLayout popAnima;
    @Bind(R.id.call_police_to_dismiss)
    RelativeLayout callPoliceToDismiss;
    @Bind(R.id.loc_picker)
    ImageView locPicker;
    @Bind(R.id.call_time_lost_time)
    EditText callTimeLostTime;

    private Calendar calendar;
    /**
     * 当前的年月日时分
     * year,monthOfYear,dayOfMonth,hourOfDay,minute
     * <p/>
     * 当前时间 毫秒格式
     * cruTime
     */

    private int year;
    private int monthOfYear;
    private int dayOfMonth;
    private int hourOfDay;
    private int minute;
    private long cruTime;

    private int timeflag = 0;  //0 未选择  1等于或当前时间之前  3当前时间之后
    private int dateflag = 0; //0 未选择  1 今天之前  2今天   3今天以后
    private final static int CALL_PHONE = 2;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_police);
        ButterKnife.bind(this);
        sp = getSharedPreferences("config", MODE_PRIVATE);
        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy年MM月dd日 HH:mm:ss ");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        callTimeLostTime.setText(str);
        //1.开启服务
        Intent service_intent = new Intent(this, GPSService.class);
        startService(service_intent);

        initData();


    }

    private void initData() {
        callPolicePos.setText(sp.getString("loseAddress", "请输入丢失地址"));
        calendar = Calendar.getInstance();

        cruTime = calendar.getTimeInMillis();
        year = calendar.get(Calendar.YEAR);
        monthOfYear = calendar.get(Calendar.MONTH);
        dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
        minute = calendar.get(Calendar.MINUTE);
    }


    @OnClick({R.id.call_police_cancel_btn, R.id.time_picker,
            R.id.date_picker, R.id.call_police_first,/* R.id.call_police_second,
            R.id.call_police_third,*/ R.id.call_police_sure_tv, R.id.loc_picker})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.call_police_cancel_btn:
                onBackPressed();

                break;

            case R.id.time_picker:
                TimePickerDialog timePickerDialog = new TimePickerDialog(CallPoliceActivity.this, new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hour, int min) {
                        Calendar c = Calendar.getInstance();
                        String dateTime;
                        int month;
                        month = monthOfYear + 1;
                        String strMonth = month < 10 ? "0" + month : "" + month;
                        String strDay = dayOfMonth < 10 ? "0" + dayOfMonth : "" + dayOfMonth;
                        String strHourOfDay = hour < 10 ? "0" + hour : "" + hour;
                        String strMinute = min < 10 ? "0" + min : "" + min;

                        dateTime = year + strMonth + strDay + strHourOfDay + strMinute; //20160506XXXX  设置的时间

                        try {
                            c.setTime(new SimpleDateFormat("yyyyMMddHHmm").parse(dateTime));
                            long ntime = c.getTimeInMillis();
                            if (dateflag == 1 | dateflag == 0) {
                                callPoliceLostTime.setText(hour + "点" + min + "分");
                            } else {
                                if (ntime <= cruTime) {
                                    //假设为选择今天   设置时间在今当前时间之前
                                    callPoliceLostTime.setText(hour + "点" + min + "分");
                                    timeflag = 1;
                                } else {
                                    Toast.makeText(CallPoliceActivity.this, "选择时间不能超过当前时间", Toast.LENGTH_SHORT).show();
                                    timeflag = 3;
                                }

                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                    }
                }, hourOfDay, minute, true);

                timePickerDialog.show();
                break;
            case R.id.date_picker:
                DatePickerDialog datePickerDialog = getDatePickerDialog();
                datePickerDialog.show();
                break;
            case R.id.call_police_first:

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                // 设置参数
                alertDialog.setTitle("报警").setIcon(R.mipmap.ic_launcher)
                        .setMessage("请先拨打110报警,进行信息确认,在进行保险理赔")
                        .setPositiveButton("拨打110", new DialogInterface.OnClickListener() {// 积极

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {

                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "110"));
                                if (ActivityCompat.checkSelfPermission(CallPoliceActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    ActivityCompat.requestPermissions(CallPoliceActivity.this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
                                    return;
                                }
                                isCAllPolice += 1;
                                startActivityForResult(intent, CALL_PHONE);
                            }
                        }).setNegativeButton("取消", null);
                alertDialog.create().show();
                break;

            case R.id.call_police_sure_tv:
                if (callPoliceSureCb.isChecked()) {
                    callPoliceToDismiss.setVisibility(View.GONE);
                } else {
                    Toast.makeText(CallPoliceActivity.this, "请阅读说明并确认", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.loc_picker:
                if (!checkNetWorkState()) {
                    ToastUtil.getToast("亲，网络连了么？", getApplicationContext());
                    return;
                }
                Intent service_intent = new Intent(this, GPSService.class);
                startService(service_intent);
                checkLocalPermission();
                Intent intent = new Intent(this, LocationActivity.class);
                startActivityForResult(intent, 1);
                break;
        }
    }


    int isCAllPolice = 0;

    private void checkLocalPermission() {
        //2.检查权限
        //checkSelfPermission  1.环境变量2。具体需要检查的权限
        int checkresult = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        //PackageManager.PERMISSION_GRANTED同意 PackageManager.PERMISSION_DENIED拒绝
        if (checkresult == PackageManager.PERMISSION_GRANTED) {
            //该权限被同意了

        } else {
            //没有获得该授权
            //3.申请授权
            //1.环境变量2.权限数组3.请求的状态码
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);

        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ACCESS_FINE_LOCATION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //addData();
        } else {
            Toast.makeText(this, "申请权限", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isCAllPolice == 1) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            // 设置参数
            alertDialog.setTitle("保险报警").setIcon(R.mipmap.ic_launcher)
                    .setMessage("请拨打95518,进行信息确认,在进行保险理赔")
                    .setPositiveButton("拨打95518", new DialogInterface.OnClickListener() {// 积极

                        @Override
                        public void onClick(DialogInterface dialog,
                                            int which) {

                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "95518"));
                            if (ActivityCompat.checkSelfPermission(CallPoliceActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(CallPoliceActivity.this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
                                return;
                            }
                            isCAllPolice += 1;
                            startActivityForResult(intent, CALL_PHONE);
                        }
                    }).setNegativeButton("取消", null);
            alertDialog.create().show();

        }
    }

    /**
     * 检查网络是否连接
     *
     * @return
     */


    private boolean checkNetWorkState() {
        ConnectivityManager con = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
        boolean internet = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
        if (wifi | internet) {
            return true;
            //执行相关操作
        } else {
            return false;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case 1:
                String location = data.getStringExtra("loseAddress");
                callPoliceLostPos.setText(location);
                break;
            case CALL_PHONE:
                Intent skipInsurance = new Intent(CallPoliceActivity.this, InsuranceClaimsActivity.class);
                startActivity(skipInsurance);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 日期选择框
     *
     * @return
     */
    @NonNull
    private DatePickerDialog getDatePickerDialog() {
        return new DatePickerDialog(CallPoliceActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int ye, int monthYear, int dayMonth) {
                String dateTime, dateTimeN;
                long tDatetime;
                int month;
                int monthN;
                //当天的零点零分
                Calendar cal = Calendar.getInstance();
                monthN = monthOfYear + 1;
                String strMonthN = monthN < 10 ? "0" + monthN : "" + monthN;
                String dayOfMonthN = dayOfMonth < 10 ? "0" + dayOfMonth : "" + dayOfMonth;
                dateTimeN = year + strMonthN + dayOfMonthN;
                //选择的当天的零点零分
                Calendar c = Calendar.getInstance();
                month = monthYear + 1;
                String strMonth = month < 10 ? "0" + month : "" + month;
                String strDay = dayMonth < 10 ? "0" + dayMonth : "" + dayMonth;
                dateTime = ye + strMonth + strDay;
                try {
                    c.setTime(new SimpleDateFormat("yyyyMMdd").parse(dateTime));
                    cal.setTime(new SimpleDateFormat("yyyyMMdd").parse(dateTimeN));
                    long ntime = c.getTimeInMillis();
                    tDatetime = cal.getTimeInMillis();
                    monthYear = monthYear + 1;
                    if (ntime < tDatetime) {
                        callPoliceLostDate.setText(ye + "年" + monthYear + "月" + dayMonth + "日");
                        dateflag = 1;
                    } else if (ntime == tDatetime) {
                        //选择今天时  判断选择时间 是否大于当前 时间
                        if (timeflag == 3) {
                            Toast.makeText(CallPoliceActivity.this, "选择日期不能超过当前日期", Toast.LENGTH_SHORT).show();
                        } else {
                            callPoliceLostDate.setText(ye + "年" + monthYear + "月" + dayMonth + "日");
                        }
                        dateflag = 2;
                    } else if (ntime > tDatetime) {
                        dateflag = 3;
                        Toast.makeText(CallPoliceActivity.this, "选择日期不能超过当前日期", Toast.LENGTH_SHORT).show();
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }, year, monthOfYear, dayOfMonth);
    }
}
